﻿@implements IDialogContentComponent<AppRoleDto>
@rendermode InteractiveServer
@inject Frogsoft.Permission.PermissionService _permissionService
@using Frogsoft.Permission.Dtos
@using Microsoft.AspNetCore.Authorization
@using System.Diagnostics
@attribute [Authorize(Policy = "system_permission_role")]

<FluentTreeView Items="@Items" @bind-SelectedItem="@SelectedItem" LazyLoadItems="false">
    <ItemTemplate>
        <FluentCheckbox Style="margin-right: 12px;" @bind-Value="@(((PermissionTreeDto)context).LAY_CHECKED)">
            @context.Text
            <span style="color: var(--accent-fill-rest); margin: 0 4px;">
                @(context.Items == null ? "" : $"[{context.Items.Count()}]")
            </span>
        </FluentCheckbox>
    </ItemTemplate>
</FluentTreeView>

<!-- Footer -->
<FluentDialogFooter>
    <FluentButton Appearance="Appearance.Accent"                      
                  OnClick="@SaveAsync">
        Save
    </FluentButton>
    <FluentButton Appearance="Appearance.Neutral"
                  OnClick="@CancelAsync">
        Cancel
    </FluentButton>
</FluentDialogFooter>

@code {
    private ITreeViewItem? SelectedItem;
    private IEnumerable<ITreeViewItem> Items = new List<ITreeViewItem>();

    [Parameter]
    public AppRoleDto Content { get; set; } = default!;

    [CascadingParameter]
    public FluentDialog? Dialog { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Items = await _permissionService.GetAllPermissionAsTree(Content.Id);
        this.StateHasChanged();
        Debug.WriteLine(Items.Count());
    }

    private List<PermissionTreeDto> GetCheckedPermissions(IEnumerable<ITreeViewItem> items)
    {
        var result = new List<PermissionTreeDto>();
        foreach (var item in items.Cast<PermissionTreeDto>())
        {
            // 如果当前节点被选中，添加到结果列表
            if (item.LAY_CHECKED)
            {
                result.Add(item);
            }

            // 如果有子节点，递归处理
            if (item._Items != null && item._Items.Any())
            {
                result.AddRange(GetCheckedPermissions(item._Items));
            }
        }
        return result;
    }

    private async Task SaveAsync()
    {
        try
        {
            // 获取所有勾选的权限（包括子节点）
            var checkedPermissions = GetCheckedPermissions(Items);
            
            // 保存更新后的权限
            _permissionService.UpdatePermission(Content.Id, checkedPermissions);
            
            await Dialog!.CloseAsync(DialogResult.Ok(Content));
        }
        catch (Exception ex)
        {
            await Dialog!.CloseAsync(DialogResult.Cancel());
        }
    }

    private async Task CancelAsync()
    {
        await Dialog!.CancelAsync();
    }
}
